package com.health.healthproject.controller;

import com.health.healthproject.common.Result;
import com.health.healthproject.util.FileUploadUtil;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileUploadController {

    /**
     * 下载文件
     * @param filePath 文件相对路径
     * @return 文件资源
     */
    @GetMapping("/download")
    public void downloadFile(HttpServletResponse response, @RequestParam("path") String filePath) {
        String basePath = "D:/health_project/uploads/";
        String filename = filePath.substring(filePath.lastIndexOf("/") + 1);
        FileUploadUtil.download(response,basePath+filePath,filename);
        /*try {
            // 检查文件是否存在
            if (!FileUploadUtil.exists(filePath)) {
                return ResponseEntity.notFound().build();
            }

            // 获取文件资源
            Resource resource = FileUploadUtil.getFileResource(filePath);
            // UrlResource resource = new UrlResource(filePath);
            // 从文件路径中提取文件名

            byte[] fileContent;
            try (InputStream inputStream = resource.getInputStream()) {
                fileContent = StreamUtils.copyToByteArray(inputStream);
            }
            // 设置文件的MediaType
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=\"" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()) + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(fileContent);
        } catch (IOException e) {
            return ResponseEntity.badRequest().build();
        }*/
    }

    @PostMapping("/upload")
    public Result<List<String>> uploadFiles(
            @RequestParam("files") List<MultipartFile> files,
            @RequestParam("type") String type) {
        try {
            FileUploadUtil.BusinessType businessType = FileUploadUtil.BusinessType.valueOf(type.toUpperCase());
            List<String> uploadedPaths = FileUploadUtil.uploadFiles(files, businessType);
            return Result.success(uploadedPaths);
        } catch (IOException e) {
            return Result.error("文件上传失败: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return Result.error("无效的业务类型");
        }
    }
}